package com.bdv.md.en;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.swing.JOptionPane;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;

import com.bdv.md.controller.xmlattribute.Parameter;
import com.bdv.md.job.TestJob;

public class TestClass {

	public static void main(String[] args) {
//		String msg = "*756*110*12345msisdn*12345meterid*12345token*1#";
//		String[] ussdCommandsResp = msg.substring(1).split("[*#]");
//		System.out.print("");
		
//		String trxId = "TransactionID Request";
//		String accessCode = "USSD Number";
//		String utilityCode = "service ID for Specific Partner";
//		String meterNumber = "MSISDN of Meter";
//		String meterID = "ID of Meter";
//		String tokenNumber = "Token of Meter";
//		
//		Parameter param = new Parameter(trxId, accessCode, utilityCode, meterNumber, meterID, tokenNumber);
//		
//		TselXMLObj token = new TselXMLObj();
//		token.setType("SubmitToken");
//		token.setParam(param);
//		
//		try {
//			 
//			String xmlResult = null;
//			StreamResult xmlStreamResult = new StreamResult(new ByteArrayOutputStream());; 
//			
//			JAXBContext jaxbContext = JAXBContext.newInstance(TselXMLObj.class);
//			XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
//			
//			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
////            jaxbMarshaller.setProperty("jaxb.encoding", "ISO-8859-1");
////            jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
//	 
//			// output pretty printed
//			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//			
////			ByteArrayOutputStream baos = new ByteArrayOutputStream();
////            XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(baos, (String) jaxbMarshaller.getProperty(Marshaller.JAXB_ENCODING));
////            xmlStreamWriter.writeStartDocument((String) jaxbMarshaller.getProperty(Marshaller.JAXB_ENCODING), "1.0");
////            
////            jaxbMarshaller.marshal(token, xmlStreamWriter);
////            xmlStreamWriter.writeEndDocument();
////            xmlStreamWriter.close();
//            
//			
//			jaxbMarshaller.marshal(token, xmlStreamResult);
//			
////			System.out.println(xmlStreamResult.getOutputStream().toString());
////			
////			System.out.println(new String(baos.toByteArray()));
//			
//			String xmlString = xmlStreamResult.getOutputStream().toString();
//			JAXBContext jc = JAXBContext.newInstance(TselXMLObj.class);
//	        Unmarshaller unmarshaller = jc.createUnmarshaller();
//	        StreamSource xmlSource = new StreamSource(new StringReader(xmlString));
//	        TselXMLObj je = (TselXMLObj)unmarshaller.unmarshal(xmlSource);
//	        
//	        System.out.println("SOURCE:\n"+xmlString);
//	        System.out.println("VALUE : "+je.toString());
//	        
//	      } catch (Exception e) {
//	    	  e.printStackTrace();
//	      }
		
		
		// QUARTZ TESTING
//		JobDetail job = JobBuilder.newJob(TestJob.class)
//				.withIdentity("jobSatu", "group1").build();
//		job.getJobDataMap().put(TestJob.testValue, "Test Ganti STRING");
//		
//		Trigger trigger = TriggerBuilder.newTrigger()
//				.withIdentity("trigSatu", "group1")
//				.withSchedule(
//					SimpleScheduleBuilder.simpleSchedule()
//						.withIntervalInSeconds(2)
//						.repeatForever())
//				.build();
//
//		Scheduler scheduler;
//		try {
//			scheduler = new StdSchedulerFactory().getScheduler();
//			scheduler.start();
//			scheduler.scheduleJob(job, trigger);
//			
//
//			String time =JOptionPane.showInputDialog(null,"Masukan jumlah waktu");
//			System.out.println("Update Trigger");
//			
//			TriggerKey oldTriggerKey = new TriggerKey("trigSatu", "group1");
//			Trigger newTrigger = TriggerBuilder.newTrigger()
//				    .withIdentity("trigSatu", "group1")
//					.withSchedule(
//							SimpleScheduleBuilder.simpleSchedule()
//								.withIntervalInMilliseconds(Integer.parseInt(time))
//								.repeatForever())
//				    .startNow()
//				    .build();
//			
//			scheduler.rescheduleJob(oldTriggerKey,newTrigger);
//			
//		} catch (SchedulerException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}

		
//		String xml = "<name>Rein</name>";
//		PostMethod post = new PostMethod("http://192.168.1.211:8080/Portal/test");   
//	    try {
//	    	
//	        StringRequestEntity requestEntity = new StringRequestEntity(xml);
//	        post.setRequestEntity(requestEntity);
//	        
//	        post.setRequestEntity(requestEntity);
//	        post.setRequestHeader("Content-type",
//	                "text/xml; charset=UTF-8");
//	        
//	        
//	        org.apache.commons.httpclient.HttpClient httpclient = new org.apache.commons.httpclient.HttpClient();
//
//	        int result = httpclient.executeMethod(post);
//	        
//	        System.out.println(post);
//	        System.out.println("Response status code: " + result);
//	        System.out.println("Response body: ");
//	        System.out.println(post.getResponseBodyAsString());
//	    } catch (IOException e) {
//	        e.printStackTrace();
//	    } finally {
//	        post.releaseConnection();
//	    }
//		String xml = "<test>isiTest</test>";
//		String url ="http://180.250.80.173:80/Integration/";
//		
//		System.out.print( httpRequestPost(url, xml));
		
		
//		System.out.print(UrlList.MGT_ALARM_REQUEST.toString());

		for(int i = 0; i<100;i++){
			String trxId = randomAlphaNumeric(4);
			String trxId2 = randomS(trxId);
			System.out.println(trxId+" "+trxId2);			
		}
	}
	
	private static String randomS(String trxId){
		int sPos = rnd.nextInt(5);
		if(sPos == 0) return "s"+trxId;
		if(sPos == 5) return trxId+"s";
		
		String fTrxId = trxId.substring(0, sPos);
		String lTrxId = trxId.substring(sPos);
		return fTrxId+"s"+lTrxId;
	}

	private static final String ALPHANUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrtuvwxyz";
	private static Random rnd = new Random();
	
	protected static String randomAlphaNumeric( int idLength ) 
	{
	   StringBuilder sb = new StringBuilder( idLength );
	   for( int i = 0; i < idLength; i++ ) 
	      sb.append( ALPHANUM.charAt( rnd.nextInt(ALPHANUM.length()) ) );
	   return sb.toString();
	}
	
	private static Class getClass (Object a){
		return a.getClass();
	}
	
	private static String httpRequestPost(String url, String xml){
		System.out.println("POST TO "+url+" XML : "+xml);
		PostMethod post = new PostMethod(url);   
		String response = null;
	    try {
	    	
	        StringRequestEntity requestEntity = new StringRequestEntity(xml);
	        post.setRequestEntity(requestEntity);
	        
	        post.setRequestEntity(requestEntity);
	        post.setRequestHeader("Content-type",  "text/xml; charset=UTF-8");
	        org.apache.commons.httpclient.HttpClient httpclient = new org.apache.commons.httpclient.HttpClient();
	        int result = httpclient.executeMethod(post);
	        
	        response = post.getResponseBodyAsString();
	        
	        System.out.println(post);
	        System.out.println("Response status code: " + result);
	        System.out.println("Response body: ");
	        System.out.println(response);
	        
	    } catch (IOException e) {
	        e.printStackTrace();
	        return e.getStackTrace().toString();
	    } finally {
	        post.releaseConnection();
	    }
	    return response;
	}
	
}
